from django.shortcuts import render, get_object_or_404, redirect
from .models import Recipe, Tag, RecipeImage, Category
from .forms import RecipeForm
from django.db.models import Q
from django.urls import reverse
from django.contrib import messages
import random

def index(request):
    # 基本排序：评分高优先，再按推荐、再按创建时间
    # 注意：rating 为空的可能被排到后面；所以用 order_by('-rating') 即可
    rating_choices = ['0', '1', '2', '3', '4', '5']
    selected_tags = request.GET.getlist('tags')

    recipes = Recipe.objects.all().order_by('-rating', '-is_recommended', '-created_at')
    tags = Tag.objects.all()
    categories = Category.objects.all()

    # 过滤条件
    keyword = request.GET.get('q')
    tag_filter = request.GET.get('tag')
    category_filter = request.GET.get('category')
    difficulty_filter = request.GET.get('difficulty')
    max_minutes = request.GET.get('max_minutes')  # 如果想筛选耗时
    takeaway_filter = request.GET.get('takeaway')  # '1' 为只看可外卖

    if keyword:
        recipes = recipes.filter(Q(title__icontains=keyword) | Q(tags__name__icontains=keyword)).distinct()
    if tag_filter:
        recipes = recipes.filter(tags__id=tag_filter)
    if category_filter:
        recipes = recipes.filter(category_id=category_filter)
    if difficulty_filter:
        recipes = recipes.filter(difficulty=difficulty_filter)
    if max_minutes:
        try:
            mm = int(max_minutes)
            recipes = recipes.filter(estimated_minutes__lte=mm)
        except ValueError:
            pass
    if takeaway_filter == '1':
        recipes = recipes.filter(is_takeaway_available=True)

    # 推荐逻辑：优先评分 >=4 的（如果存在），随机从中取 up to 5
    top_candidates = Recipe.objects.filter(rating__gte=4).order_by('-rating')
    if top_candidates.exists():
        top_list = list(top_candidates)
        recommended = random.sample(top_list, min(5, len(top_list)))
    else:
        # fallback: 手动推荐或随机最近的
        recs = Recipe.objects.filter(is_recommended=True)[:5]
        if recs.exists():
            recommended = list(recs)
        else:
            recommended = list(Recipe.objects.order_by('-created_at')[:5])

    return render(request, 'recipes/index.html', {
        'recipes': recipes,
        'tags': tags,
        'categories': categories,
        'recommended': recommended,
        'rating_choices':rating_choices,
        'selected_tags':selected_tags,
    })

def recipe_detail(request, recipe_id):
    recipe = get_object_or_404(Recipe, pk=recipe_id)
    # 更新查看次数
    Recipe.objects.filter(pk=recipe_id).update(views=recipe.views + 1)
    images = recipe.images.all()
    return render(request, 'recipes/detail.html', {'recipe': recipe, 'images': images})

def add_recipe(request):
    categories = Category.objects.all()
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES)
        files = request.FILES.getlist('images')
        if form.is_valid():
            recipe = form.save(commit=False)

            # 处理分类
            category_id = request.POST.get('category')
            if category_id:
                recipe.category_id = int(category_id)

            # 处理额外字段
            recipe.location = request.POST.get('location', '')
            recipe.shop_name = request.POST.get('shop_name', '')
            rating = request.POST.get('rating')
            if rating:
                try:
                    recipe.rating = float(rating)
                except ValueError:
                    recipe.rating = None

            recipe.save()
            form.save_m2m()

            # 保存图片
            for f in files:
                RecipeImage.objects.create(recipe=recipe, image=f)

            messages.success(request, "已添加菜谱。")
            return redirect('index')
        else:
            messages.error(request, "请修正表单错误后重试。")
    else:
        form = RecipeForm()

    return render(request, 'recipes/add.html', {
        'form': form,
        'categories': categories,
    })

def edit_recipe(request, recipe_id):
    recipe = get_object_or_404(Recipe, id=recipe_id)
    categories = Category.objects.all()

    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES, instance=recipe)
        files = request.FILES.getlist('images')

        if form.is_valid():
            recipe = form.save(commit=False)

            category_id = request.POST.get('category')
            if category_id:
                recipe.category_id = int(category_id)

            recipe.location = request.POST.get('location', '')
            recipe.shop_name = request.POST.get('shop_name', '')
            rating = request.POST.get('rating')
            try:
                recipe.rating = float(rating)
            except (ValueError, TypeError):
                recipe.rating = None

            recipe.save()
            form.save_m2m()

            # 追加上传的图片
            for f in files:
                RecipeImage.objects.create(recipe=recipe, image=f)

            messages.success(request, "菜谱已更新。")
            return redirect('recipe_detail', recipe.id)
        else:
            messages.error(request, "请修正表单错误后重试。")
    else:
        form = RecipeForm(instance=recipe)

    return render(request, 'recipes/edit.html', {
        'form': form,
        'recipe': recipe,
        'categories': categories,
    })


def delete_recipe(request, recipe_id):
    recipe = get_object_or_404(Recipe, id=recipe_id)
    recipe.delete()
    messages.success(request, "已删除菜谱。")
    return redirect('index')

def delete_image(request, image_id):
    image = get_object_or_404(RecipeImage, id=image_id)
    recipe_id = image.recipe.id
    try:
        image.image.delete()  # 删除文件
    except Exception:
        pass
    image.delete()        # 删除数据库记录
    messages.success(request, "已删除图片。")
    return redirect('edit_recipe', recipe_id=recipe_id)

def increase_made_count(request, recipe_id):
    recipe = get_object_or_404(Recipe, pk=recipe_id)
    recipe.made_count += 1
    recipe.save()
    messages.success(request, "做过次数已增加。")
    return redirect('recipe_detail', recipe_id=recipe.id)

# 标签管理（保留并完善）
def manage_tags(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name:
            Tag.objects.get_or_create(name=name.strip())
            messages.success(request, f"已创建标签：{name}")
    tags = Tag.objects.all()
    return render(request, 'recipes/manage_tags.html', {'tags': tags})

def delete_tag(request, tag_id):
    tag = get_object_or_404(Tag, id=tag_id)
    tag.delete()
    messages.success(request, "已删除标签。")
    return redirect('manage_tags')

def edit_tag(request, tag_id):
    tag = get_object_or_404(Tag, id=tag_id)
    new_name = request.POST.get('new_name', '').strip()
    if new_name and new_name != tag.name:
        tag.name = new_name
        tag.save()
        messages.success(request, "标签已更新。")
    return redirect('manage_tags')

# 分类管理（Category）
def manage_categories(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name:
            Category.objects.get_or_create(name=name.strip())
            messages.success(request, f"已创建分类：{name}")
    categories = Category.objects.all()
    return render(request, 'recipes/manage_categories.html', {'categories': categories})

def delete_category(request, category_id):
    cat = get_object_or_404(Category, id=category_id)
    cat.delete()
    messages.success(request, "已删除分类。")
    return redirect('manage_categories')

def edit_category(request, category_id):
    cat = get_object_or_404(Category, id=category_id)
    new_name = request.POST.get('new_name', '').strip()
    if new_name and new_name != cat.name:
        cat.name = new_name
        cat.save()
        messages.success(request, "分类已更新。")
    return redirect('manage_categories')

# 帮我选 — 简单的智能推荐接口
def suggest_recipe(request):
    recipes = Recipe.objects.all()

    # 获取参数
    max_minutes = request.GET.get('max_minutes')
    min_rating = request.GET.get('min_rating')
    price_tier = request.GET.get('price_tier')
    difficulty = request.GET.get('difficulty')
    only_takeaway = request.GET.get('only_takeaway')
    prefer_category = request.GET.get('prefer_category')
    tags = request.GET.getlist('tags')
    keyword = request.GET.get('keyword')
    prefer_made_count = request.GET.get('prefer_made_count')

    # 过滤耗时
    if max_minutes:
        try:
            mm = int(max_minutes)
            recipes = recipes.filter(estimated_minutes__lte=mm)
        except ValueError:
            pass

    # 过滤最低评分
    if min_rating:
        try:
            mr = float(min_rating)
            recipes = recipes.filter(rating__gte=mr)
        except ValueError:
            pass

    # 价格档次过滤
    if price_tier:
        recipes = recipes.filter(price_tier=price_tier)

    # 难易度过滤
    if difficulty:
        recipes = recipes.filter(difficulty=difficulty)

    # 仅外卖
    if only_takeaway == '1':
        recipes = recipes.filter(is_takeaway_available=True)

    # 优先分类
    if prefer_category:
        try:
            cid = int(prefer_category)
            pref = recipes.filter(category_id=cid)
            if pref.exists():
                recipes = pref
        except ValueError:
            pass

    # 标签过滤（多选）
    if tags:
        for tag_id in tags:
            try:
                tid = int(tag_id)
                recipes = recipes.filter(tags__id=tid)
            except ValueError:
                pass

    # 关键词过滤（在标题、描述、材料里模糊搜索）
    if keyword:
        from django.db.models import Q
        recipes = recipes.filter(
            Q(title__icontains=keyword) |
            Q(description__icontains=keyword) |
            Q(ingredients__icontains=keyword)
        )

    # 根据是否优先吃过次数多排序
    if prefer_made_count == '1':
        recipes = recipes.order_by('-made_count')
    else:
        # 默认评分高优先，后续随机
        recipes = recipes.order_by('-rating')

    if not recipes.exists():
        messages.error(request, "没有符合条件的菜谱。")
        return redirect('index')

    # 随机选一个
    import random
    recipe = random.choice(list(recipes))
    return redirect('recipe_detail', recipe_id=recipe.id)
